<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
</head>

<body>
    <header class="aui-bar aui-bar-nav main-header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            容器绑定物料
        </div>
    </header>
    <script id="chkBillTemp" type="text/x-dot-template">

        {{~ it:value:index}}
        <li class="aui-list-item" ">
            <div class="aui-media-list-item-inner">
                <div class="aui-list-item-inner ">
                    <div class="aui-list-item-text">
                        <div class="aui-list-item-title aui-font-size-14">
                            物料编码：{{= it[index].mrlCode }}
                        </div>
                    </div>
                    <div class="aui-list-item-title aui-font-size-14">
                        物料名称：{{= it[index].mrlName }}
                    </div>
                    <div class="aui-list-item-title aui-font-size-14">
                        批次号：{{= it[index].ext05 }}
                    </div>
                    <div class="aui-list-item-title aui-font-size-14">
                        数量：{{= it[index].qty }}
                    </div>
                   
                </div>
            </div>
        </li>
        {{~}}

    </script>
    <div class="aui-bar aui-bar-nav sub-header"></div>
    <div class="aui-content aui-margin-b-15" style="margin-top:50px;padding-bottom: 50px;">
        <div class="white_background">
            <ul class="aui-list aui-form-list">
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">库位</div>
                        <div class="aui-list-item-input">
                            <input type="text" placeholder="选择/扫描 库位" id="workCellCode" value=""
                                onclick="getIdSelector();" />
                        </div>
                        <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="goSelectWorkCell()"></i>
                    </div>
                </li>
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">物料号</div>
                        <div class="aui-list-item-input">
                            <input type="text" placeholder="选择物料" id="mrlCode" value="" onclick="getIdSelector();"
                                disabled onfocus="focusFn(this)">
                        </div>
                        <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="goSelectMrl()"></i>
                    </div>
                </li>
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">批次号</div>
                        <div class="aui-list-item-input">
                            <input type="number" id="lotCode">
                        </div>
                    </div>
                </li>
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">容器条码</div>
                        <input type="text" class="aui-input" placeholder="请扫描容器" style="width: 80%;" id="trayyinfoid"
                            onclick="getIdSelector();" onfocus="focusFn(this)">

                    </div>
                </li>

            </ul>
        </div>
        <div class="aui-btn aui-btn-info aui-btn-block" onclick="save()" id="submitButton">绑定</div>
        <div style="width:100%;margin-top:2%;"></div>
        <div class="aui-btn aui-btn-info aui-btn-block" onclick="doSearch()">查询</div>
        <!-- <div style="background-color:white; height: 100%;width: 100%;margin-top:2%;">
            <table class="table" style='width:100%;' id="table">
                <thead>
                    <tr
                        style="text-align: center;background-color: #f2dcdc;color: #467aa7;font-size: 12px;font-weight: bold;">
                        <td algin='center'>物料编码</td>
                        <td algin='center'>物料名称</td>
                        <td algin='center'>批次号</td>
                        <td algin='center'>数量</td>
                    </tr>
                </thead>
                <tbody id="tbodyHtml">
                </tbody>
            </table>
        </div> -->
        <div class="white_background">
            <div style="background-color:white; height: 100%;width: 100%;margin-top:2%;margin-bottom:2%;"
                id="tbodyHtml">

            </div>
        </div>


        <footer class="aui-bar aui-bar-tab" id="footer">
            <div class="aui-bar-tab-item" tapmode id="scan" onclick="doScan()">
                <i class="aui-iconfont aui-icon-scan aui-text-epblue" style="font-size: 1.8rem"></i>
            </div>
        </footer>


</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/doT.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/clickThrottle.js"></script>
<script type="text/javascript">
    var scanRule = ""; //箱码解析规则
    var workCellGid = ""; //库位GID
    var workCellCode = ""; //库位编码
    var workCellName = ""; //库位名称
    var mrlCode = "";//物料编码
    var mrlName = "";//物料名称
    var bindList = "";//绑定物料数据

    //初始化查询仓库下拉框
    apiready = function () {

        $("#workCellCode").focus();

        //查询箱码解析规则
        initScanRule();
    }

    // 获取光标所在组件的id
    function getIdSelector() {
        var e = event || window.event;
        var el = e.srcElement || e.target;
        idSelector = el.id;
        $("#" + el.id).select();
    }

    //查询扫描规则
    function initScanRule() {
        var serverUrl = localStorage.getItem('serverUrl');
        var un = localStorage.getItem("un");
        var url = serverUrl + "/app/getTmScanRule";
        var data = {
            values: {
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    scanRule = myobj.scanRule
                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });
    }
    //扫描
    function doScan() {
        var moduleScanner = api.require('moduleScanner');
        var params = {
            top: 150, //扫描窗口的上边距
            width: 250, //扫描窗口的宽
            height: 250, //扫描窗口的高
            useColor: false, //是否使用自己设定的颜色(startColor和endColor),
            //如果不使用设定的颜色就使用默认的那张网格图
            startColor: '#0F08C8FF', //渐变起始颜色
            endColor: '#7F08C8FF', //渐变结束颜色
            animTime: 2200, //扫描动画时间,单位为毫秒
        };
        moduleScanner.toScannerActivityForResult(params, function (ret, err) {
            //alert(ret);扫码的结果都是编码
            //1：容器条码
            if (idSelector == 'trayyinfoid') {

                $("#trayyinfoid").val(ret);

                getTrayInfo();
                //2:箱码
            } else if (idSelector == 'workCellCode') {

                $("#workCellCode").val(ret);
                //查询库位
                getWorkCell(ret, idSelector);

                //扫描容器
            } else if (idSelector == 'tm') {

                $("#tm").val(ret);
                //查询库位
                tmSplit(ret);

            }
        });
    }

    //绑定
    function save() {
        if (!clickThrottle()) {
            return;
        }

        var trayyinfoid = $("#trayyinfoid").val();
        var tm = $("#tm").val();

        const submitButton = document.getElementById('submitButton');

        submitButton.style.pointerEvents = "none"
        //容器
        if (trayyinfoid == "" || trayyinfoid == null || trayyinfoid == undefined) {
            api.toast({
                msg: '请扫描容器！',
                duration: 3000
            });
            submitButton.style.pointerEvents = "auto"
            return;
        }
        if (bindList.length == 0) {
            api.toast({
                msg: '没有可绑定数据！',
                duration: 3000
            });
            submitButton.style.pointerEvents = "auto"
            return;
        }

        var isAllZero = true;
        for (var i = 0; i < bindList.length; i++) {
            var ss = document.getElementById('bindQty_' + i).value;
            if (parseFloat(ss) > 0) {
                isAllZero = false;
                break;
            }
        }
        if (isAllZero) {
            api.toast({
                msg: '没有绑定的数据，请输入绑定数量',
                duration: 3000
            });
            submitButton.style.pointerEvents = "auto"
            return;
        }

        api.showProgress({
            title: '保存中...',
        });
        var un = localStorage.getItem("un");
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/wmTrayinfoBindNewac_Bind";
        var data = {
            values: {
                trayyinfoid: trayyinfoid, //容器
                dataList: bindList,
                checkFlag: "Y",//是否需要校验箱是否入库 Y-是 其他则不校验
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    api.hideProgress();
                    submitButton.style.pointerEvents = "auto"
                    api.toast({
                        msg: "绑定成功",
                        duration: 3000
                    });

                    var bindNum = myobj.bindNum
                    //清空表单数据
                    $("#bindNum").val(bindNum);
                    $("#tm").val("");
                    getTrayInfo()
                    doSearch()

                    //光标回到箱码
                    $("#tm").focus();
                    $("#tm").select();
                    idSelector = "tm";
                } else {

                    $("#tm").val("");
                    $("#tm").select();
                    idSelector = "tm";
                    api.hideProgress();
                    submitButton.style.pointerEvents = "auto"
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {

                $("#tm").val("");
                $("#tm").select();
                idSelector = "tm";
                api.hideProgress();
                submitButton.style.pointerEvents = "auto"
                // alert(JSON.stringify(err));
                alert("连接超时，请耐心等待");
            }
        });
    }

    //自动保存
    function saveAuto() {
        var trayyinfoid = $("#trayyinfoid").val();
        var tm = $("#tm").val();
        /* var supplierCode = $("#supplierCode").val();
        var mrlCode = $("#mrlCode").val();
        var lotCode = $("#lotCode").val();
        var qty = $("#qty").val();
        var boxnum = $("#boxnum").val(); */

        //容器
        if (trayyinfoid == "" || trayyinfoid == null || trayyinfoid == undefined) {
            return;
        }

        //箱码
        if (tm == "" || tm == null || tm == undefined) {
            return;
        }
        //物料号非空校验
        // if (mrlCode == "" || mrlCode == null || mrlCode == undefined) {
        //     return;
        // }
        // //批次号非空校验
        // if (lotCode == "" || lotCode == null || lotCode == undefined) {
        //     return;
        // }

        // //数量非空校验
        // if (qty == "" || qty == null || qty == undefined || parseFloat(qty) <= 0) {
        //     return;
        // }

        // //箱号非空校验
        // if (boxnum == "" || boxnum == null || boxnum == undefined) {
        //     return;
        // }

        save();
    }


    // //扫描箱码
    // function toScanner(flag) {
    //     var moduleScanner = api.require('moduleScanner');
    //     var params = {
    //         top: 150, //扫描窗口的上边距
    //         width: 250, //扫描窗口的宽
    //         height: 250, //扫描窗口的高
    //         useColor: false, //是否使用自己设定的颜色(startColor和endColor),
    //         //如果不使用设定的颜色就使用默认的那张网格图
    //         startColor: '#0F08C8FF', //渐变起始颜色
    //         endColor: '#7F08C8FF', //渐变结束颜色
    //         animTime: 2200, //扫描动画时间,单位为毫秒
    //     };
    //     moduleScanner.toScannerActivityForResult(params, function (ret, err) {

    //         var sm = ret;
    //         //容器
    //         if (flag == 1) {
    //             var text = document.getElementById("trayyinfoid");
    //             text.value = sm;
    //             getTrayInfo();
    //             //箱码
    //         } else {

    //             //箱码解析
    //             tmSplit(sm);
    //         }
    //     });
    // }

    //箱码监听回车事件
    $("#tm").on('keypress', function (e) {
        var keycode = e.keyCode;
        var tm = $(this).val();
        if (keycode == '13') {
            if (tm != null && tm != "" && tm != undefined) {
                $("#tm").blur();
                console.log(tm);
                //箱码解析
                tmSplit(tm);
            }

        }
    });

    //选择物料
    function goSelectMrl() {
        api.openWin({
            name: 'usmSelectMrl',
            url: 'usmSelectMrl.html',
            pageParam: {
                name: "wmTrayinfo_BindAcMrl",
            }
        });
    }

    //物料选择后回调函数
    function setMrl(sysid, code, name) {
        $("#mrlCode").val(code + ":" + name);
        mrlCode = code;
        mrlName = name;
        doSearch()
    }

    //容器监听回车事件
    $("#trayyinfoid").on('keypress', function (e) {
        var keycode = e.keyCode;
        var tm = $(this).val();
        if (keycode == '13') {
            if (tm != null && tm != "" && tm != undefined) {
                console.log(tm);
                $("#trayyinfoid").val(tm);
                $("#tm").focus();
                getTrayInfo();
            }

        }
    });

    //6：选择库位
    function goSelectWorkCell() {
        var tm = $("#tm").val();
        api.openWin({
            name: 'uwmSelectWorkCell_ac',
            url: 'uwmSelectWorkCell_ac.html',
            pageParam: {
                flag: "in_rk",
                name: "wmTrayinfo_BindAcMrl",
                tm: tm,
                workCenterGid: "",
                relWorkCellGid: "",
                workCellFlag: ""
            }
        });
    }

    //库位选择后回调函数
    function setWorkCell(id, code, name) {
        workCellGid = id;
        workCellCode = code;
        workCellName = name;
        document.getElementById('workCellCode').value = code + ":" + name;
        // getWorkCell(workCellCode, "workCellCode")
        $("#boxnum").focus();
        var e = "boxnum";
        idSelector = e;
    }

    //7；PDA自带扫描回车事件-库位
    $("#workCellCode").on('keypress', function (e) { //#keyword为input文本框
        var keycode = e.keyCode;
        var sm = $(this).val();
        if (keycode == '13') {

            //仓库编码
            $("#workCellCode").val(sm);
            //校验改箱码是否存在
            getWorkCell(sm, "workCellCode");
        }
    });

    //5:库位扫描校验
    function getWorkCell(code, inputId) {
        var un = localStorage.getItem("un");
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getWorkCenterByCell";
        var data = {
            values: {
                flag: "in_rk", //库内库间标识（out_kn库内  out_kj库间,in_rk入库出库）
                workCenterGid: "", //仓库GID
                workCellCode: code, //库位编码
                workCellGid: "",
                relWorkCellGid: "", //调入库位
                tm: "",
                workCellFlag: "", //原库位调入库位flag
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    var list = eval(myobj.list);
                    workCellGid = list[0].cellid;
                    workCellCode = list[0].cellcode;
                    workCellName = list[0].cellname;
                    document.getElementById(inputId).value = workCellCode + ":" + workCellName;
                    $("#traynum").focus();
                    idSelector = "traynum";
                    doSearch()

                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                    $("#workCellCode").focus();
                    $("#workCellCode").select();
                }
            }
        });
    }

    //查询
    function doSearch() {


        if (workCellCode == "" || workCellCode == null || workCellCode == undefined) {
            api.toast({
                msg: '请扫描/选择 库位！',
                duration: 3000
            });
            return;
        }

        var lotCode = $("#lotCode").val();
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getBindMrlList";
        var data = {
            values: {
                workCellCode: workCellCode,
                mrlCode: mrlCode,
                lotCode: lotCode,
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");

                //返回成功
                if (myobj.code == "0") {
                    var list = eval(myobj.list);
                    bindList = list;
                    var html = "";
                    var bindQty = "";
                    for (var i = 0; i < list.length; i++) {
                        bindQty = "bindQty_" + i
                        html += "<div class='aui-btn-info aui-btn-block' style='margin-bottom: 10px;color: black !important;background-color: #addbef !important;height: 140px;padding: 0.2rem 0.2rem;font-size: 15px;border-radius: 8px;'>";
                        html += "<table style='width:100%;'>";
                        html += "<tr style='width:100%;'><td style='width:100%;' colspan='2'>库位编码：" + list[i].workCellCode + "</td></tr>";
                        html += "<tr style='width:100%;'><td style='width:100%;' colspan='2'>物料编码：" + list[i].mrlCode + "</td></tr>";
                        html += "<tr style='width:100%;'><td style='width:100%;' colspan='2'>批次号：" + list[i].lotCode + "</td></tr>";
                        html += "<tr style='width:100%;'><td style='width:100%;' colspan='2'>供应商：" + list[i].ysupplier + "</td></tr>";
                        html += "<tr style='width:100%;'><td style='width:50%;'>库存数量：" + list[i].qyt + "</td><td style='width:50%;'>绑定数量：<input id='" + bindQty + "'  style='width:40%;' value='" + list[i].bdQyt + "' onblur='saveBindQyt(\"" + list[i].workCellCode + "\",\"" + list[i].mrlCode + "\",\"" + list[i].lotCode + "\",\"" + list[i].ysupplier + "\",\"" + list[i].qyt + "\")' ></input></td></tr> ";
                        html += "</table></div>";
                    }
                    $api.html($api.byId("tbodyHtml"), html);

                    $("#traynum").focus();
                    idSelector = "traynum";
                    //失败
                } else if (myobj.code == "1") {

                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });
    }

    function saveBindQyt(workCellCode, mrlCode, lotCode, ysupplier, qyt) {

        console.log(qyt)
        for (var i = 0; i < bindList.length; i++) {
            var ss = document.getElementById('bindQty_' + i).value;
            if (workCellCode === bindList[i].workCellCode && mrlCode === bindList[i].mrlCode && lotCode === bindList[i].lotCode && ysupplier === bindList[i].ysupplier) {
                if (parseFloat(ss) > parseFloat(qyt)) {
                    api.toast({
                        msg: '绑定数量不能大于库存数量！',
                        duration: 3000
                    });
                    return;
                } else {
                    bindList[i].bdQyt = ss;
                    console.log(bindList[i].bdQyt)
                }
            }
        }

    }


    function getTrayInfo() {
        var sm = $("#trayyinfoid").val();
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/doSearchTrayac";
        var data = {
            values: {
                sm: sm,
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");

                //返回成功
                if (myobj.code == "0") {
                    var list = eval(myobj.list);

                    // var evaluation = doT.template($api.dom('#chkBillTemp').innerHTML);
                    // $api.dom('#mrlList').innerHTML = evaluation(list);

                    //失败
                } else if (myobj.code == "1") {
                    $("#trayyinfoid").val("");
                    $("#trayyinfoid").select();
                    idSelector = "trayyinfoid";

                    //清空表格数据
                    // $api.html($api.byId("tbodyHtml"), "");
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                $("#trayyinfoid").val("");
                $("#trayyinfoid").select();
                idSelector = "trayyinfoid";
                api.hideProgress();
                // alert(JSON.stringify(err));
                alert("连接超时，请耐心等待");
            }
        });
    }

    //扫描之后箱码解析
    function tmSplit(sm) {
        $("#tm").val(sm);
        //直接解析
        if (scanRule == "old") {

            //本地解析
            localAnalyze(sm);

        } else {

            //后台解析
            postAnalyze(sm);
        }
    }

    //本地解析
    function localAnalyze(sm) {
        var arr = sm.split(",");
        $("#supplierCode").val(arr[0]);
        $("#mrlCode").val(arr[1]);
        $("#qty").val(arr[2]);
        $("#lotCode").val(arr[3]);
        $("#tmID").val(arr[4]);
        $("#boxnum").val(arr[9]);
        //箱号选中
        $("#tm").select();

        //自动保存
        saveAuto();
    }

    //后台解析箱码
    function postAnalyze(sm) {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/analysisBarCodeCommon";
        var data = {
            values: {
                tm: sm, //箱码
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == '0') {

                    var map = myobj.data;
                    for (var key in map) {
                        $("#" + key).val(map[key]);
                    }

                    //自动保存
                    saveAuto();
                } else if (myobj.code == '1') {

                    $("#tm").val("");
                    $("#tm").select();
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                // alert(JSON.stringify(err));
                alert("连接超时，请耐心等待");
            }
        });
    }

    //返回按钮
    function closeWin() {
        api.closeWin({});
    }
    function focusFn(ele) {
        $api.attr(ele, 'readonly', 'readonly');
        setTimeout(() => {
            $api.removeAttr(ele, 'readonly');
        }, 200);
    };
</script>

</html>